home *** CD-ROM | disk | FTP | other *** search
/ Software of the Month Club 2000 October / Software of the Month - Ultimate Collection Shareware 277.iso / pc / PROGRAMS / UTILITY / WINLINUX / DATA1.CAB / programs_-_kernel_source / FS / BUFFER.C < prev    next >
Encoding:
C/C++ Source or Header  |  1999-09-17  |  44.8 KB  |  1,843 lines

  1. /*
  2.  *  linux/fs/buffer.c
  3.  *
  4.  *  Copyright (C) 1991, 1992  Linus Torvalds
  5.  */
  6.  
  7. /*
  8.  *  'buffer.c' implements the buffer-cache functions. Race-conditions have
  9.  * been avoided by NEVER letting an interrupt change a buffer (except for the
  10.  * data, of course), but instead letting the caller do it.
  11.  */
  12.  
  13. /* Start bdflush() with kernel_thread not syscall - Paul Gortmaker, 12/95 */
  14.  
  15. /* Removed a lot of unnecessary code and simplified things now that
  16.  * the buffer cache isn't our primary cache - Andrew Tridgell 12/96
  17.  */
  18.  
  19. /* Speed up hash, lru, and free list operations.  Use gfp() for allocating
  20.  * hash table, use SLAB cache for buffer heads. -DaveM
  21.  */
  22.  
  23. /* Added 32k buffer block sizes - these are required older ARM systems.
  24.  * - RMK
  25.  */
  26.  
  27. #include <linux/malloc.h>
  28. #include <linux/locks.h>
  29. #include <linux/errno.h>
  30. #include <linux/swap.h>
  31. #include <linux/swapctl.h>
  32. #include <linux/smp_lock.h>
  33. #include <linux/vmalloc.h>
  34. #include <linux/blkdev.h>
  35. #include <linux/sysrq.h>
  36. #include <linux/file.h>
  37. #include <linux/init.h>
  38. #include <linux/quotaops.h>
  39.  
  40. #include <asm/uaccess.h>
  41. #include <asm/io.h>
  42. #include <asm/bitops.h>
  43.  
  44. #define NR_SIZES 7
  45. static char buffersize_index[65] =
  46. {-1,  0,  1, -1,  2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1,
  47.   4, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1,
  48.   5, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1,
  49.  -1, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1,
  50.   6};
  51.  
  52. #define BUFSIZE_INDEX(X) ((int) buffersize_index[(X)>>9])
  53. #define MAX_BUF_PER_PAGE (PAGE_SIZE / 512)
  54. #define NR_RESERVED (2*MAX_BUF_PER_PAGE)
  55. #define MAX_UNUSED_BUFFERS NR_RESERVED+20 /* don't ever have more than this 
  56.                          number of unused buffer heads */
  57.  
  58. /*
  59.  * Hash table mask..
  60.  */
  61. static unsigned long bh_hash_mask = 0;
  62.  
  63. static int grow_buffers(int size);
  64.  
  65. static struct buffer_head ** hash_table;
  66. static struct buffer_head * lru_list[NR_LIST] = {NULL, };
  67. static struct buffer_head * free_list[NR_SIZES] = {NULL, };
  68.  
  69. static kmem_cache_t *bh_cachep;
  70.  
  71. static struct buffer_head * unused_list = NULL;
  72. static struct buffer_head * reuse_list = NULL;
  73. static struct wait_queue * buffer_wait = NULL;
  74.  
  75. static int nr_buffers = 0;
  76. static int nr_buffers_type[NR_LIST] = {0,};
  77. static int nr_buffer_heads = 0;
  78. static int nr_unused_buffer_heads = 0;
  79. static int nr_hashed_buffers = 0;
  80.  
  81. /* This is used by some architectures to estimate available memory. */
  82. int buffermem = 0;
  83.  
  84. /* Here is the parameter block for the bdflush process. If you add or
  85.  * remove any of the parameters, make sure to update kernel/sysctl.c.
  86.  */
  87.  
  88. #define N_PARAM 9
  89.  
  90. /* The dummy values in this structure are left in there for compatibility
  91.  * with old programs that play with the /proc entries.
  92.  */
  93. union bdflush_param{
  94.     struct {
  95.         int nfract;  /* Percentage of buffer cache dirty to 
  96.                 activate bdflush */
  97.         int ndirty;  /* Maximum number of dirty blocks to write out per
  98.                 wake-cycle */
  99.         int nrefill; /* Number of clean buffers to try to obtain
  100.                 each time we call refill */
  101.         int nref_dirt; /* Dirty buffer threshold for activating bdflush
  102.                   when trying to refill buffers. */
  103.         int dummy1;    /* unused */
  104.         int age_buffer;  /* Time for normal buffer to age before 
  105.                     we flush it */
  106.         int age_super;  /* Time for superblock to age before we 
  107.                    flush it */
  108.         int dummy2;    /* unused */
  109.         int dummy3;    /* unused */
  110.     } b_un;
  111.     unsigned int data[N_PARAM];
  112. } bdf_prm = {{40, 500, 64, 256, 15, 30*HZ, 5*HZ, 1884, 2}};
  113.  
  114. /* These are the min and max parameter values that we will allow to be assigned */
  115. int bdflush_min[N_PARAM] = {  0,  10,    5,   25,  0,   1*HZ,   1*HZ, 1, 1};
  116. int bdflush_max[N_PARAM] = {100,5000, 2000, 2000,100, 600*HZ, 600*HZ, 2047, 5};
  117.  
  118. void wakeup_bdflush(int);
  119.  
  120. /*
  121.  * Rewrote the wait-routines to use the "new" wait-queue functionality,
  122.  * and getting rid of the cli-sti pairs. The wait-queue routines still
  123.  * need cli-sti, but now it's just a couple of 386 instructions or so.
  124.  *
  125.  * Note that the real wait_on_buffer() is an inline function that checks
  126.  * if 'b_wait' is set before calling this, so that the queues aren't set
  127.  * up unnecessarily.
  128.  */
  129. void __wait_on_buffer(struct buffer_head * bh)
  130. {
  131.     struct task_struct *tsk = current;
  132.     struct wait_queue wait;
  133.  
  134.     bh->b_count++;
  135.     wait.task = tsk;
  136.     add_wait_queue(&bh->b_wait, &wait);
  137. repeat:
  138.     tsk->state = TASK_UNINTERRUPTIBLE;
  139.     run_task_queue(&tq_disk);
  140.     if (buffer_locked(bh)) {
  141.         schedule();
  142.         goto repeat;
  143.     }
  144.     tsk->state = TASK_RUNNING;
  145.     remove_wait_queue(&bh->b_wait, &wait);
  146.     bh->b_count--;
  147. }
  148.  
  149. /* Call sync_buffers with wait!=0 to ensure that the call does not
  150.  * return until all buffer writes have completed.  Sync() may return
  151.  * before the writes have finished; fsync() may not.
  152.  */
  153.  
  154. /* Godamity-damn.  Some buffers (bitmaps for filesystems)
  155.  * spontaneously dirty themselves without ever brelse being called.
  156.  * We will ultimately want to put these in a separate list, but for
  157.  * now we search all of the lists for dirty buffers.
  158.  */
  159. static int sync_buffers(kdev_t dev, int wait)
  160. {
  161.     int i, retry, pass = 0, err = 0;
  162.     struct buffer_head * bh, *next;
  163.  
  164.     /* One pass for no-wait, three for wait:
  165.      * 0) write out all dirty, unlocked buffers;
  166.      * 1) write out all dirty buffers, waiting if locked;
  167.      * 2) wait for completion by waiting for all buffers to unlock.
  168.      */
  169.     do {
  170.         retry = 0;
  171. repeat:
  172.         /* We search all lists as a failsafe mechanism, not because we expect
  173.          * there to be dirty buffers on any of the other lists.
  174.          */
  175.         bh = lru_list[BUF_DIRTY];
  176.         if (!bh)
  177.             goto repeat2;
  178.         for (i = nr_buffers_type[BUF_DIRTY]*2 ; i-- > 0 ; bh = next) {
  179.             if (bh->b_list != BUF_DIRTY)
  180.                 goto repeat;
  181.             next = bh->b_next_free;
  182.             if (!lru_list[BUF_DIRTY])
  183.                 break;
  184.             if (dev && bh->b_dev != dev)
  185.                 continue;
  186.             if (buffer_locked(bh)) {
  187.                 /* Buffer is locked; skip it unless wait is
  188.                  * requested AND pass > 0.
  189.                  */
  190.                 if (!wait || !pass) {
  191.                     retry = 1;
  192.                     continue;
  193.                 }
  194.                 wait_on_buffer (bh);
  195.                 goto repeat;
  196.             }
  197.  
  198.             /* If an unlocked buffer is not uptodate, there has
  199.              * been an IO error. Skip it.
  200.              */
  201.             if (wait && buffer_req(bh) && !buffer_locked(bh) &&
  202.                 !buffer_dirty(bh) && !buffer_uptodate(bh)) {
  203.                 err = -EIO;
  204.                 continue;
  205.             }
  206.  
  207.             /* Don't write clean buffers.  Don't write ANY buffers
  208.              * on the third pass.
  209.              */
  210.             if (!buffer_dirty(bh) || pass >= 2)
  211.                 continue;
  212.  
  213.             /* Don't bother about locked buffers.
  214.              *
  215.              * XXX We checked if it was locked above and there is no
  216.              * XXX way we could have slept in between. -DaveM
  217.              */
  218.             if (buffer_locked(bh))
  219.                 continue;
  220.             bh->b_count++;
  221.             next->b_count++;
  222.             bh->b_flushtime = 0;
  223.             ll_rw_block(WRITE, 1, &bh);
  224.             bh->b_count--;
  225.             next->b_count--;
  226.             retry = 1;
  227.         }
  228.  
  229.     repeat2:
  230.         bh = lru_list[BUF_LOCKED];
  231.         if (!bh)
  232.             break;
  233.         for (i = nr_buffers_type[BUF_LOCKED]*2 ; i-- > 0 ; bh = next) {
  234.             if (bh->b_list != BUF_LOCKED)
  235.                 goto repeat2;
  236.             next = bh->b_next_free;
  237.             if (!lru_list[BUF_LOCKED])
  238.                 break;
  239.             if (dev && bh->b_dev != dev)
  240.                 continue;
  241.             if (buffer_locked(bh)) {
  242.                 /* Buffer is locked; skip it unless wait is
  243.                  * requested AND pass > 0.
  244.                  */
  245.                 if (!wait || !pass) {
  246.                     retry = 1;
  247.                     continue;
  248.                 }
  249.                 wait_on_buffer (bh);
  250.                 goto repeat2;
  251.             }
  252.         }
  253.  
  254.         /* If we are waiting for the sync to succeed, and if any dirty
  255.          * blocks were written, then repeat; on the second pass, only
  256.          * wait for buffers being written (do not pass to write any
  257.          * more buffers on the second pass).
  258.          */
  259.     } while (wait && retry && ++pass<=2);
  260.     return err;
  261. }
  262.  
  263. void sync_dev(kdev_t dev)
  264. {
  265.     sync_buffers(dev, 0);
  266.     sync_supers(dev);
  267.     sync_inodes(dev);
  268.     sync_buffers(dev, 0);
  269.     DQUOT_SYNC(dev);
  270.     /*
  271.      * FIXME(eric) we need to sync the physical devices here.
  272.      * This is because some (scsi) controllers have huge amounts of
  273.      * cache onboard (hundreds of Mb), and we need to instruct
  274.      * them to commit all of the dirty memory to disk, and we should
  275.      * not return until this has happened.
  276.      *
  277.      * This would need to get implemented by going through the assorted
  278.      * layers so that each block major number can be synced, and this
  279.      * would call down into the upper and mid-layer scsi.
  280.      */
  281. }
  282.  
  283. int fsync_dev(kdev_t dev)
  284. {
  285.     sync_buffers(dev, 0);
  286.     sync_supers(dev);
  287.     sync_inodes(dev);
  288.     DQUOT_SYNC(dev);
  289.     return sync_buffers(dev, 1);
  290. }
  291.  
  292. asmlinkage int sys_sync(void)
  293. {
  294.     lock_kernel();
  295.     fsync_dev(0);
  296.     unlock_kernel();
  297.     return 0;
  298. }
  299.  
  300. /*
  301.  *    filp may be NULL if called via the msync of a vma.
  302.  */
  303.  
  304. int file_fsync(struct file *filp, struct dentry *dentry)
  305. {
  306.     struct inode * inode = dentry->d_inode;
  307.     struct super_block * sb;
  308.     kdev_t dev;
  309.  
  310.     /* sync the inode to buffers */
  311.     write_inode_now(inode);
  312.  
  313.     /* sync the superblock to buffers */
  314.     sb = inode->i_sb;
  315.     wait_on_super(sb);
  316.     if (sb->s_op && sb->s_op->write_super)
  317.         sb->s_op->write_super(sb);
  318.  
  319.     /* .. finally sync the buffers to disk */
  320.     dev = inode->i_dev;
  321.     return sync_buffers(dev, 1);
  322. }
  323.  
  324. asmlinkage int sys_fsync(unsigned int fd)
  325. {
  326.     struct file * file;
  327.     struct dentry * dentry;
  328.     struct inode * inode;
  329.     int err;
  330.  
  331.     lock_kernel();
  332.     err = -EBADF;
  333.     file = fget(fd);
  334.     if (!file)
  335.         goto out;
  336.  
  337.     dentry = file->f_dentry;
  338.     if (!dentry)
  339.         goto out_putf;
  340.  
  341.     inode = dentry->d_inode;
  342.     if (!inode)
  343.         goto out_putf;
  344.  
  345.     err = -EINVAL;
  346.     if (!file->f_op || !file->f_op->fsync)
  347.         goto out_putf;
  348.  
  349.     /* We need to protect against concurrent writers.. */
  350.     down(&inode->i_sem);
  351.     err = file->f_op->fsync(file, dentry);
  352.     up(&inode->i_sem);
  353.  
  354. out_putf:
  355.     fput(file);
  356. out:
  357.     unlock_kernel();
  358.     return err;
  359. }
  360.  
  361. asmlinkage int sys_fdatasync(unsigned int fd)
  362. {
  363.     struct file * file;
  364.     struct dentry * dentry;
  365.     struct inode * inode;
  366.     int err;
  367.  
  368.     lock_kernel();
  369.     err = -EBADF;
  370.     file = fget(fd);
  371.     if (!file)
  372.         goto out;
  373.  
  374.     dentry = file->f_dentry;
  375.     if (!dentry)
  376.         goto out_putf;
  377.  
  378.     inode = dentry->d_inode;
  379.     if (!inode)
  380.         goto out_putf;
  381.  
  382.     err = -EINVAL;
  383.     if (!file->f_op || !file->f_op->fsync)
  384.         goto out_putf;
  385.  
  386.     /* this needs further work, at the moment it is identical to fsync() */
  387.     down(&inode->i_sem);
  388.     err = file->f_op->fsync(file, dentry);
  389.     up(&inode->i_sem);
  390.  
  391. out_putf:
  392.     fput(file);
  393. out:
  394.     unlock_kernel();
  395.     return err;
  396. }
  397.  
  398. void invalidate_buffers(kdev_t dev)
  399. {
  400.     int i;
  401.     int nlist;
  402.     struct buffer_head * bh;
  403.  
  404.     for(nlist = 0; nlist < NR_LIST; nlist++) {
  405.         bh = lru_list[nlist];
  406.         for (i = nr_buffers_type[nlist]*2 ; --i > 0 ; bh = bh->b_next_free) {
  407.             if (bh->b_dev != dev)
  408.                 continue;
  409.             wait_on_buffer(bh);
  410.             if (bh->b_dev != dev)
  411.                 continue;
  412.             if (bh->b_count)
  413.                 continue;
  414.             bh->b_flushtime = 0;
  415.             clear_bit(BH_Protected, &bh->b_state);
  416.             clear_bit(BH_Uptodate, &bh->b_state);
  417.             clear_bit(BH_Dirty, &bh->b_state);
  418.             clear_bit(BH_Req, &bh->b_state);
  419.         }
  420.     }
  421. }
  422.  
  423. #define _hashfn(dev,block) (((unsigned)(HASHDEV(dev)^block)) & bh_hash_mask)
  424. #define hash(dev,block) hash_table[_hashfn(dev,block)]
  425.  
  426. static inline void remove_from_hash_queue(struct buffer_head * bh)
  427. {
  428.     struct buffer_head **pprev = bh->b_pprev;
  429.     if (pprev) {
  430.         struct buffer_head * next = bh->b_next;
  431.         if (next) {
  432.             next->b_pprev = pprev;
  433.             bh->b_next = NULL;
  434.         }
  435.         *pprev = next;
  436.         bh->b_pprev = NULL;
  437.     }
  438.     nr_hashed_buffers--;
  439. }
  440.  
  441. static inline void remove_from_lru_list(struct buffer_head * bh)
  442. {
  443.     if (!(bh->b_prev_free) || !(bh->b_next_free))
  444.         panic("VFS: LRU block list corrupted");
  445.     if (bh->b_dev == B_FREE)
  446.         panic("LRU list corrupted");
  447.     bh->b_prev_free->b_next_free = bh->b_next_free;
  448.     bh->b_next_free->b_prev_free = bh->b_prev_free;
  449.  
  450.     if (lru_list[bh->b_list] == bh)
  451.          lru_list[bh->b_list] = bh->b_next_free;
  452.     if (lru_list[bh->b_list] == bh)
  453.          lru_list[bh->b_list] = NULL;
  454.     bh->b_next_free = bh->b_prev_free = NULL;
  455. }
  456.  
  457. static inline void remove_from_free_list(struct buffer_head * bh)
  458. {
  459.     int isize = BUFSIZE_INDEX(bh->b_size);
  460.     if (!(bh->b_prev_free) || !(bh->b_next_free))
  461.         panic("VFS: Free block list corrupted");
  462.     if(bh->b_dev != B_FREE)
  463.         panic("Free list corrupted");
  464.     if(!free_list[isize])
  465.         panic("Free list empty");
  466.     if(bh->b_next_free == bh)
  467.          free_list[isize] = NULL;
  468.     else {
  469.         bh->b_prev_free->b_next_free = bh->b_next_free;
  470.         bh->b_next_free->b_prev_free = bh->b_prev_free;
  471.         if (free_list[isize] == bh)
  472.              free_list[isize] = bh->b_next_free;
  473.     }
  474.     bh->b_next_free = bh->b_prev_free = NULL;
  475. }
  476.  
  477. static void remove_from_queues(struct buffer_head * bh)
  478. {
  479.     if(bh->b_dev == B_FREE) {
  480.         remove_from_free_list(bh); /* Free list entries should not be
  481.                           in the hash queue */
  482.         return;
  483.     }
  484.     nr_buffers_type[bh->b_list]--;
  485.     remove_from_hash_queue(bh);
  486.     remove_from_lru_list(bh);
  487. }
  488.  
  489. static inline void put_last_lru(struct buffer_head * bh)
  490. {
  491.     if (bh) {
  492.         struct buffer_head **bhp = &lru_list[bh->b_list];
  493.  
  494.         if (bh == *bhp) {
  495.             *bhp = bh->b_next_free;
  496.             return;
  497.         }
  498.  
  499.         if(bh->b_dev == B_FREE)
  500.             panic("Wrong block for lru list");
  501.  
  502.         /* Add to back of free list. */
  503.         remove_from_lru_list(bh);
  504.         if(!*bhp) {
  505.             *bhp = bh;
  506.             (*bhp)->b_prev_free = bh;
  507.         }
  508.  
  509.         bh->b_next_free = *bhp;
  510.         bh->b_prev_free = (*bhp)->b_prev_free;
  511.         (*bhp)->b_prev_free->b_next_free = bh;
  512.         (*bhp)->b_prev_free = bh;
  513.     }
  514. }
  515.  
  516. static inline void put_last_free(struct buffer_head * bh)
  517. {
  518.     if (bh) {
  519.         struct buffer_head **bhp = &free_list[BUFSIZE_INDEX(bh->b_size)];
  520.  
  521.         bh->b_dev = B_FREE;  /* So it is obvious we are on the free list. */
  522.  
  523.         /* Add to back of free list. */
  524.         if(!*bhp) {
  525.             *bhp = bh;
  526.             bh->b_prev_free = bh;
  527.         }
  528.  
  529.         bh->b_next_free = *bhp;
  530.         bh->b_prev_free = (*bhp)->b_prev_free;
  531.         (*bhp)->b_prev_free->b_next_free = bh;
  532.         (*bhp)->b_prev_free = bh;
  533.     }
  534. }
  535.  
  536. static void insert_into_queues(struct buffer_head * bh)
  537. {
  538.     /* put at end of free list */
  539.     if(bh->b_dev == B_FREE) {
  540.         put_last_free(bh);
  541.     } else {
  542.         struct buffer_head **bhp = &lru_list[bh->b_list];
  543.  
  544.         if(!*bhp) {
  545.             *bhp = bh;
  546.             bh->b_prev_free = bh;
  547.         }
  548.  
  549.         if (bh->b_next_free)
  550.             panic("VFS: buffer LRU pointers corrupted");
  551.  
  552.         bh->b_next_free = *bhp;
  553.         bh->b_prev_free = (*bhp)->b_prev_free;
  554.         (*bhp)->b_prev_free->b_next_free = bh;
  555.         (*bhp)->b_prev_free = bh;
  556.  
  557.         nr_buffers_type[bh->b_list]++;
  558.  
  559.         /* Put the buffer in new hash-queue if it has a device. */
  560.         bh->b_next = NULL;
  561.         bh->b_pprev = NULL;
  562.         if (bh->b_dev) {
  563.             struct buffer_head **bhp = &hash(bh->b_dev, bh->b_blocknr);
  564.             struct buffer_head *next = *bhp;
  565.  
  566.             if (next) {
  567.                 bh->b_next = next;
  568.                 next->b_pprev = &bh->b_next;
  569.             }
  570.             *bhp = bh;
  571.             bh->b_pprev = bhp;
  572.         }
  573.         nr_hashed_buffers++;
  574.     }
  575. }
  576.  
  577. struct buffer_head * find_buffer(kdev_t dev, int block, int size)
  578. {        
  579.     struct buffer_head * next;
  580.  
  581.     next = hash(dev,block);
  582.     for (;;) {
  583.         struct buffer_head *tmp = next;
  584.         if (!next)
  585.             break;
  586.         next = tmp->b_next;
  587.         if (tmp->b_blocknr != block || tmp->b_size != size || tmp->b_dev != dev)
  588.             continue;
  589.         next = tmp;
  590.         break;
  591.     }
  592.     return next;
  593. }
  594.  
  595. /*
  596.  * Why like this, I hear you say... The reason is race-conditions.
  597.  * As we don't lock buffers (unless we are reading them, that is),
  598.  * something might happen to it while we sleep (ie a read-error
  599.  * will force it bad). This shouldn't really happen currently, but
  600.  * the code is ready.
  601.  */
  602. struct buffer_head * get_hash_table(kdev_t dev, int block, int size)
  603. {
  604.     struct buffer_head * bh;
  605.     bh = find_buffer(dev,block,size);
  606.     if (bh)
  607.         bh->b_count++;
  608.     return bh;
  609. }
  610.  
  611. unsigned int get_hardblocksize(kdev_t dev)
  612. {
  613.     /*
  614.      * Get the hard sector size for the given device.  If we don't know
  615.      * what it is, return 0.
  616.      */
  617.     if (hardsect_size[MAJOR(dev)] != NULL) {
  618.         int blksize = hardsect_size[MAJOR(dev)][MINOR(dev)];
  619.         if (blksize != 0)
  620.             return blksize;
  621.     }
  622.  
  623.     /*
  624.      * We don't know what the hardware sector size for this device is.
  625.      * Return 0 indicating that we don't know.
  626.      */
  627.     return 0;
  628. }
  629.  
  630. void set_blocksize(kdev_t dev, int size)
  631. {
  632.     extern int *blksize_size[];
  633.     int i, nlist;
  634.     struct buffer_head * bh, *bhnext;
  635.  
  636.     if (!blksize_size[MAJOR(dev)])
  637.         return;
  638.  
  639.     /* Size must be a power of two, and between 512 and PAGE_SIZE */
  640.     if (size > PAGE_SIZE || size < 512 || (size & (size-1)))
  641.         panic("Invalid blocksize passed to set_blocksize");
  642.  
  643.     if (blksize_size[MAJOR(dev)][MINOR(dev)] == 0 && size == BLOCK_SIZE) {
  644.         blksize_size[MAJOR(dev)][MINOR(dev)] = size;
  645.         return;
  646.     }
  647.     if (blksize_size[MAJOR(dev)][MINOR(dev)] == size)
  648.         return;
  649.     sync_buffers(dev, 2);
  650.     blksize_size[MAJOR(dev)][MINOR(dev)] = size;
  651.  
  652.     /* We need to be quite careful how we do this - we are moving entries
  653.      * around on the free list, and we can get in a loop if we are not careful.
  654.      */
  655.     for(nlist = 0; nlist < NR_LIST; nlist++) {
  656.         bh = lru_list[nlist];
  657.         for (i = nr_buffers_type[nlist]*2 ; --i > 0 ; bh = bhnext) {
  658.             if(!bh)
  659.                 break;
  660.  
  661.             bhnext = bh->b_next_free; 
  662.             if (bh->b_dev != dev)
  663.                  continue;
  664.             if (bh->b_size == size)
  665.                  continue;
  666.             bhnext->b_count++;
  667.             wait_on_buffer(bh);
  668.             bhnext->b_count--;
  669.             if (bh->b_dev == dev && bh->b_size != size) {
  670.                 clear_bit(BH_Dirty, &bh->b_state);
  671.                 clear_bit(BH_Uptodate, &bh->b_state);
  672.                 clear_bit(BH_Req, &bh->b_state);
  673.                 bh->b_flushtime = 0;
  674.             }
  675.             remove_from_hash_queue(bh);
  676.         }
  677.     }
  678. }
  679.  
  680. /*
  681.  * We used to try various strange things. Let's not.
  682.  */
  683. static void refill_freelist(int size)
  684. {
  685.     if (!grow_buffers(size)) {
  686.         wakeup_bdflush(1);
  687.         current->policy |= SCHED_YIELD;
  688.         schedule();
  689.     }
  690. }
  691.  
  692. void init_buffer(struct buffer_head *bh, kdev_t dev, int block,
  693.          bh_end_io_t *handler, void *dev_id)
  694. {
  695.     bh->b_count = 1;
  696.     bh->b_list = BUF_CLEAN;
  697.     bh->b_flushtime = 0;
  698.     bh->b_dev = dev;
  699.     bh->b_blocknr = block;
  700.     bh->b_end_io = handler;
  701.     bh->b_dev_id = dev_id;
  702. }
  703.  
  704. static void end_buffer_io_sync(struct buffer_head *bh, int uptodate)
  705. {
  706.     mark_buffer_uptodate(bh, uptodate);
  707.     unlock_buffer(bh);
  708. }
  709.  
  710. /*
  711.  * Ok, this is getblk, and it isn't very clear, again to hinder
  712.  * race-conditions. Most of the code is seldom used, (ie repeating),
  713.  * so it should be much more efficient than it looks.
  714.  *
  715.  * The algorithm is changed: hopefully better, and an elusive bug removed.
  716.  *
  717.  * 14.02.92: changed it to sync dirty buffers a bit: better performance
  718.  * when the filesystem starts to get full of dirty blocks (I hope).
  719.  */
  720. struct buffer_head * getblk(kdev_t dev, int block, int size)
  721. {
  722.     struct buffer_head * bh;
  723.     int isize;
  724.  
  725. repeat:
  726.     bh = get_hash_table(dev, block, size);
  727.     if (bh) {
  728.         if (!buffer_dirty(bh)) {
  729.             if (buffer_uptodate(bh))
  730.                  put_last_lru(bh);
  731.             bh->b_flushtime = 0;
  732.         }
  733.         return bh;
  734.     }
  735.  
  736.     isize = BUFSIZE_INDEX(size);
  737. get_free:
  738.     bh = free_list[isize];
  739.     if (!bh)
  740.         goto refill;
  741.     remove_from_free_list(bh);
  742.  
  743.     /* OK, FINALLY we know that this buffer is the only one of its kind,
  744.      * and that it's unused (b_count=0), unlocked, and clean.
  745.      */
  746.     init_buffer(bh, dev, block, end_buffer_io_sync, NULL);
  747.     bh->b_state=0;
  748.     insert_into_queues(bh);
  749.     return bh;
  750.  
  751.     /*
  752.      * If we block while refilling the free list, somebody may
  753.      * create the buffer first ... search the hashes again.
  754.      */
  755. refill:
  756.     refill_freelist(size);
  757.     if (!find_buffer(dev,block,size))
  758.         goto get_free;
  759.     goto repeat;
  760. }
  761.  
  762. void set_writetime(struct buffer_head * buf, int flag)
  763. {
  764.     int newtime;
  765.  
  766.     if (buffer_dirty(buf)) {
  767.         /* Move buffer to dirty list if jiffies is clear. */
  768.         newtime = jiffies + (flag ? bdf_prm.b_un.age_super : 
  769.                      bdf_prm.b_un.age_buffer);
  770.         if(!buf->b_flushtime || buf->b_flushtime > newtime)
  771.              buf->b_flushtime = newtime;
  772.     } else {
  773.         buf->b_flushtime = 0;
  774.     }
  775. }
  776.  
  777.  
  778. /*
  779.  * Put a buffer into the appropriate list, without side-effects.
  780.  */
  781. static inline void file_buffer(struct buffer_head *bh, int list)
  782. {
  783.     remove_from_queues(bh);
  784.     bh->b_list = list;
  785.     insert_into_queues(bh);
  786. }
  787.  
  788. /*
  789.  * A buffer may need to be moved from one buffer list to another
  790.  * (e.g. in case it is not shared any more). Handle this.
  791.  */
  792. void refile_buffer(struct buffer_head * buf)
  793. {
  794.     int dispose;
  795.  
  796.     if(buf->b_dev == B_FREE) {
  797.         printk("Attempt to refile free buffer\n");
  798.         return;
  799.     }
  800.     if (buffer_dirty(buf))
  801.         dispose = BUF_DIRTY;
  802.     else if (buffer_locked(buf))
  803.         dispose = BUF_LOCKED;
  804.     else
  805.         dispose = BUF_CLEAN;
  806.     if(dispose != buf->b_list) {
  807.         file_buffer(buf, dispose);
  808.         if(dispose == BUF_DIRTY) {
  809.             int too_many = (nr_buffers * bdf_prm.b_un.nfract/100);
  810.  
  811.             /* This buffer is dirty, maybe we need to start flushing.
  812.              * If too high a percentage of the buffers are dirty...
  813.              */
  814.             if (nr_buffers_type[BUF_DIRTY] > too_many)
  815.                 wakeup_bdflush(1);
  816.  
  817.             /* If this is a loop device, and
  818.              * more than half of the buffers are dirty...
  819.              * (Prevents no-free-buffers deadlock with loop device.)
  820.              */
  821.             if (MAJOR(buf->b_dev) == LOOP_MAJOR &&
  822.                 nr_buffers_type[BUF_DIRTY]*2>nr_buffers)
  823.                 wakeup_bdflush(1);
  824.         }
  825.     }
  826. }
  827.  
  828. /*
  829.  * Release a buffer head
  830.  */
  831. void __brelse(struct buffer_head * buf)
  832. {
  833.     /* If dirty, mark the time this buffer should be written back. */
  834.     set_writetime(buf, 0);
  835.     refile_buffer(buf);
  836.  
  837.     if (buf->b_count) {
  838.         buf->b_count--;
  839.         return;
  840.     }
  841.     printk("VFS: brelse: Trying to free free buffer\n");
  842. }
  843.  
  844. /*
  845.  * bforget() is like brelse(), except it puts the buffer on the
  846.  * free list if it can.. We can NOT free the buffer if:
  847.  *  - there are other users of it
  848.  *  - it is locked and thus can have active IO
  849.  */
  850. void __bforget(struct buffer_head * buf)
  851. {
  852.     if (buf->b_count != 1 || buffer_locked(buf)) {
  853.         __brelse(buf);
  854.         return;
  855.     }
  856.     buf->b_count = 0;
  857.     remove_from_queues(buf);
  858.     put_last_free(buf);
  859. }
  860.  
  861. /*
  862.  * bread() reads a specified block and returns the buffer that contains
  863.  * it. It returns NULL if the block was unreadable.
  864.  */
  865. struct buffer_head * bread(kdev_t dev, int block, int size)
  866. {
  867.     struct buffer_head * bh;
  868.  
  869.     bh = getblk(dev, block, size);
  870.     touch_buffer(bh);
  871.     if (buffer_uptodate(bh))
  872.         return bh;
  873.     ll_rw_block(READ, 1, &bh);
  874.     wait_on_buffer(bh);
  875.     if (buffer_uptodate(bh))
  876.         return bh;
  877.     brelse(bh);
  878.     return NULL;
  879. }
  880.  
  881. /*
  882.  * Ok, breada can be used as bread, but additionally to mark other
  883.  * blocks for reading as well. End the argument list with a negative
  884.  * number.
  885.  */
  886.  
  887. #define NBUF 16
  888.  
  889. struct buffer_head * breada(kdev_t dev, int block, int bufsize,
  890.     unsigned int pos, unsigned int filesize)
  891. {
  892.     struct buffer_head * bhlist[NBUF];
  893.     unsigned int blocks;
  894.     struct buffer_head * bh;
  895.     int index;
  896.     int i, j;
  897.  
  898.     if (pos >= filesize)
  899.         return NULL;
  900.  
  901.     if (block < 0)
  902.         return NULL;
  903.  
  904.     bh = getblk(dev, block, bufsize);
  905.     index = BUFSIZE_INDEX(bh->b_size);
  906.  
  907.     touch_buffer(bh);
  908.     if (buffer_uptodate(bh))
  909.         return(bh);   
  910.     else ll_rw_block(READ, 1, &bh);
  911.  
  912.     blocks = (filesize - pos) >> (9+index);
  913.  
  914.     if (blocks < (read_ahead[MAJOR(dev)] >> index))
  915.         blocks = read_ahead[MAJOR(dev)] >> index;
  916.     if (blocks > NBUF) 
  917.         blocks = NBUF;
  918.  
  919. /*    if (blocks) printk("breada (new) %d blocks\n",blocks); */
  920.  
  921.  
  922.     bhlist[0] = bh;
  923.     j = 1;
  924.     for(i=1; i<blocks; i++) {
  925.         bh = getblk(dev,block+i,bufsize);
  926.         if (buffer_uptodate(bh)) {
  927.             brelse(bh);
  928.             break;
  929.         }
  930.         else bhlist[j++] = bh;
  931.     }
  932.  
  933.     /* Request the read for these buffers, and then release them. */
  934.     if (j>1)  
  935.         ll_rw_block(READA, (j-1), bhlist+1); 
  936.     for(i=1; i<j; i++)
  937.         brelse(bhlist[i]);
  938.  
  939.     /* Wait for this buffer, and then continue on. */
  940.     bh = bhlist[0];
  941.     wait_on_buffer(bh);
  942.     if (buffer_uptodate(bh))
  943.         return bh;
  944.     brelse(bh);
  945.     return NULL;
  946. }
  947.  
  948. /*
  949.  * Note: the caller should wake up the buffer_wait list if needed.
  950.  */
  951. static void put_unused_buffer_head(struct buffer_head * bh)
  952. {
  953.     if (nr_unused_buffer_heads >= MAX_UNUSED_BUFFERS) {
  954.         nr_buffer_heads--;
  955.         kmem_cache_free(bh_cachep, bh);
  956.         return;
  957.     }
  958.  
  959.     memset(bh,0,sizeof(*bh));
  960.     nr_unused_buffer_heads++;
  961.     bh->b_next_free = unused_list;
  962.     unused_list = bh;
  963. }
  964.  
  965. /* 
  966.  * We can't put completed temporary IO buffer_heads directly onto the
  967.  * unused_list when they become unlocked, since the device driver
  968.  * end_request routines still expect access to the buffer_head's
  969.  * fields after the final unlock.  So, the device driver puts them on
  970.  * the reuse_list instead once IO completes, and we recover these to
  971.  * the unused_list here.
  972.  *
  973.  * Note that we don't do a wakeup here, but return a flag indicating
  974.  * whether we got any buffer heads. A task ready to sleep can check
  975.  * the returned value, and any tasks already sleeping will have been
  976.  * awakened when the buffer heads were added to the reuse list.
  977.  */
  978. static inline int recover_reusable_buffer_heads(void)
  979. {
  980.     struct buffer_head *head = xchg(&reuse_list, NULL);
  981.     int found = 0;
  982.     
  983.     if (head) {
  984.         do {
  985.             struct buffer_head *bh = head;
  986.             head = head->b_next_free;
  987.             put_unused_buffer_head(bh);
  988.         } while (head);
  989.         found = 1;
  990.     }
  991.     return found;
  992. }
  993.  
  994. /*
  995.  * Reserve NR_RESERVED buffer heads for async IO requests to avoid
  996.  * no-buffer-head deadlock.  Return NULL on failure; waiting for
  997.  * buffer heads is now handled in create_buffers().
  998.  */ 
  999. static struct buffer_head * get_unused_buffer_head(int async)
  1000. {
  1001.     struct buffer_head * bh;
  1002.  
  1003.     recover_reusable_buffer_heads();
  1004.     if (nr_unused_buffer_heads > NR_RESERVED) {
  1005.         bh = unused_list;
  1006.         unused_list = bh->b_next_free;
  1007.         nr_unused_buffer_heads--;
  1008.         return bh;
  1009.     }
  1010.  
  1011.     /* This is critical.  We can't swap out pages to get
  1012.      * more buffer heads, because the swap-out may need
  1013.      * more buffer-heads itself.  Thus SLAB_BUFFER.
  1014.      */
  1015.     if((bh = kmem_cache_alloc(bh_cachep, SLAB_BUFFER)) != NULL) {
  1016.         memset(bh, 0, sizeof(*bh));
  1017.         nr_buffer_heads++;
  1018.         return bh;
  1019.     }
  1020.  
  1021.     /*
  1022.      * If we need an async buffer, use the reserved buffer heads.
  1023.      */
  1024.     if (async && unused_list) {
  1025.         bh = unused_list;
  1026.         unused_list = bh->b_next_free;
  1027.         nr_unused_buffer_heads--;
  1028.         return bh;
  1029.     }
  1030.  
  1031. #if 0
  1032.     /*
  1033.      * (Pending further analysis ...)
  1034.      * Ordinary (non-async) requests can use a different memory priority
  1035.      * to free up pages. Any swapping thus generated will use async
  1036.      * buffer heads.
  1037.      */
  1038.     if(!async &&
  1039.        (bh = kmem_cache_alloc(bh_cachep, SLAB_KERNEL)) != NULL) {
  1040.         memset(bh, 0, sizeof(*bh));
  1041.         nr_buffer_heads++;
  1042.         return bh;
  1043.     }
  1044. #endif
  1045.  
  1046.     return NULL;
  1047. }
  1048.  
  1049. /*
  1050.  * Create the appropriate buffers when given a page for data area and
  1051.  * the size of each buffer.. Use the bh->b_this_page linked list to
  1052.  * follow the buffers created.  Return NULL if unable to create more
  1053.  * buffers.
  1054.  * The async flag is used to differentiate async IO (paging, swapping)
  1055.  * from ordinary buffer allocations, and only async requests are allowed
  1056.  * to sleep waiting for buffer heads. 
  1057.  */
  1058. static struct buffer_head * create_buffers(unsigned long page, 
  1059.                         unsigned long size, int async)
  1060. {
  1061.     struct wait_queue wait = { current, NULL };
  1062.     struct buffer_head *bh, *head;
  1063.     long offset;
  1064.  
  1065. try_again:
  1066.     head = NULL;
  1067.     offset = PAGE_SIZE;
  1068.     while ((offset -= size) >= 0) {
  1069.         bh = get_unused_buffer_head(async);
  1070.         if (!bh)
  1071.             goto no_grow;
  1072.  
  1073.         bh->b_dev = B_FREE;  /* Flag as unused */
  1074.         bh->b_this_page = head;
  1075.         head = bh;
  1076.  
  1077.         bh->b_state = 0;
  1078.         bh->b_next_free = NULL;
  1079.         bh->b_count = 0;
  1080.         bh->b_size = size;
  1081.  
  1082.         bh->b_data = (char *) (page+offset);
  1083.         bh->b_list = 0;
  1084.     }
  1085.     return head;
  1086. /*
  1087.  * In case anything failed, we just free everything we got.
  1088.  */
  1089. no_grow:
  1090.     if (head) {
  1091.         do {
  1092.             bh = head;
  1093.             head = head->b_this_page;
  1094.             put_unused_buffer_head(bh);
  1095.         } while (head);
  1096.  
  1097.         /* Wake up any waiters ... */
  1098.         wake_up(&buffer_wait);
  1099.     }
  1100.  
  1101.     /*
  1102.      * Return failure for non-async IO requests.  Async IO requests
  1103.      * are not allowed to fail, so we have to wait until buffer heads
  1104.      * become available.  But we don't want tasks sleeping with 
  1105.      * partially complete buffers, so all were released above.
  1106.      */
  1107.     if (!async)
  1108.         return NULL;
  1109.  
  1110.     /* We're _really_ low on memory. Now we just
  1111.      * wait for old buffer heads to become free due to
  1112.      * finishing IO.  Since this is an async request and
  1113.      * the reserve list is empty, we're sure there are 
  1114.      * async buffer heads in use.
  1115.      */
  1116.     run_task_queue(&tq_disk);
  1117.  
  1118.     /* 
  1119.      * Set our state for sleeping, then check again for buffer heads.
  1120.      * This ensures we won't miss a wake_up from an interrupt.
  1121.      */
  1122.     add_wait_queue(&buffer_wait, &wait);
  1123.     current->state = TASK_UNINTERRUPTIBLE;
  1124.     if (!recover_reusable_buffer_heads())
  1125.         schedule();
  1126.     remove_wait_queue(&buffer_wait, &wait);
  1127.     current->state = TASK_RUNNING;
  1128.     goto try_again;
  1129. }
  1130.  
  1131. /* Run the hooks that have to be done when a page I/O has completed. */
  1132. static inline void after_unlock_page (struct page * page)
  1133. {
  1134.     if (test_and_clear_bit(PG_decr_after, &page->flags)) {
  1135.         atomic_dec(&nr_async_pages);
  1136. #ifdef DEBUG_SWAP
  1137.         printk ("DebugVM: Finished IO on page %p, nr_async_pages %d\n",
  1138.             (char *) page_address(page), 
  1139.             atomic_read(&nr_async_pages));
  1140. #endif
  1141.     }
  1142.     if (test_and_clear_bit(PG_swap_unlock_after, &page->flags))
  1143.         swap_after_unlock_page(page->offset);
  1144.     if (test_and_clear_bit(PG_free_after, &page->flags))
  1145.         __free_page(page);
  1146. }
  1147.  
  1148. /*
  1149.  * Free all temporary buffers belonging to a page.
  1150.  * This needs to be called with interrupts disabled.
  1151.  */
  1152. static inline void free_async_buffers (struct buffer_head * bh)
  1153. {
  1154.     struct buffer_head *tmp, *tail;
  1155.  
  1156.     /*
  1157.      * Link all the buffers into the b_next_free list,
  1158.      * so we only have to do one xchg() operation ...
  1159.      */
  1160.     tail = bh;
  1161.     while ((tmp = tail->b_this_page) != bh) {
  1162.         tail->b_next_free = tmp;
  1163.         tail = tmp;
  1164.     };
  1165.  
  1166.     /* Update the reuse list */
  1167.     tail->b_next_free = xchg(&reuse_list, NULL);
  1168.     reuse_list = bh;
  1169.  
  1170.     /* Wake up any waiters ... */
  1171.     wake_up(&buffer_wait);
  1172. }
  1173.  
  1174. static void end_buffer_io_async(struct buffer_head * bh, int uptodate)
  1175. {
  1176.     unsigned long flags;
  1177.     struct buffer_head *tmp;
  1178.     struct page *page;
  1179.  
  1180.     mark_buffer_uptodate(bh, uptodate);
  1181.     unlock_buffer(bh);
  1182.  
  1183.     /* This is a temporary buffer used for page I/O. */
  1184.     page = mem_map + MAP_NR(bh->b_data);
  1185.     if (!PageLocked(page))
  1186.         goto not_locked;
  1187.     if (bh->b_count != 1)
  1188.         goto bad_count;
  1189.  
  1190.     if (!test_bit(BH_Uptodate, &bh->b_state))
  1191.         set_bit(PG_error, &page->flags);
  1192.  
  1193.     /*
  1194.      * Be _very_ careful from here on. Bad things can happen if
  1195.      * two buffer heads end IO at almost the same time and both
  1196.      * decide that the page is now completely done.
  1197.      *
  1198.      * Async buffer_heads are here only as labels for IO, and get
  1199.      * thrown away once the IO for this page is complete.  IO is
  1200.      * deemed complete once all buffers have been visited
  1201.      * (b_count==0) and are now unlocked. We must make sure that
  1202.      * only the _last_ buffer that decrements its count is the one
  1203.      * that free's the page..
  1204.      */
  1205.     save_flags(flags);
  1206.     cli();
  1207.     bh->b_count--;
  1208.     tmp = bh;
  1209.     do {
  1210.         if (tmp->b_count)
  1211.             goto still_busy;
  1212.         tmp = tmp->b_this_page;
  1213.     } while (tmp != bh);
  1214.  
  1215.     /* OK, the async IO on this page is complete. */
  1216.     free_async_buffers(bh);
  1217.     restore_flags(flags);
  1218.     clear_bit(PG_locked, &page->flags);
  1219.     wake_up(&page->wait);
  1220.     after_unlock_page(page);
  1221.     return;
  1222.  
  1223. still_busy:
  1224.     restore_flags(flags);
  1225.     return;
  1226.  
  1227. not_locked:
  1228.     printk ("Whoops: end_buffer_io_async: async io complete on unlocked page\n");
  1229.     return;
  1230.  
  1231. bad_count:
  1232.     printk ("Whoops: end_buffer_io_async: b_count != 1 on async io.\n");
  1233.     return;
  1234. }
  1235.  
  1236. /*
  1237.  * Start I/O on a page.
  1238.  * This function expects the page to be locked and may return before I/O is complete.
  1239.  * You then have to check page->locked, page->uptodate, and maybe wait on page->wait.
  1240.  */
  1241. int brw_page(int rw, struct page *page, kdev_t dev, int b[], int size, int bmap)
  1242. {
  1243.     struct buffer_head *bh, *prev, *next, *arr[MAX_BUF_PER_PAGE];
  1244.     int block, nr;
  1245.  
  1246.     if (!PageLocked(page))
  1247.         panic("brw_page: page not locked for I/O");
  1248.     clear_bit(PG_uptodate, &page->flags);
  1249.     clear_bit(PG_error, &page->flags);
  1250.     /*
  1251.      * Allocate async buffer heads pointing to this page, just for I/O.
  1252.      * They do _not_ show up in the buffer hash table!
  1253.      * They are _not_ registered in page->buffers either!
  1254.      */
  1255.     bh = create_buffers(page_address(page), size, 1);
  1256.     if (!bh) {
  1257.         /* WSH: exit here leaves page->count incremented */
  1258.         clear_bit(PG_locked, &page->flags);
  1259.         wake_up(&page->wait);
  1260.         return -ENOMEM;
  1261.     }
  1262.     nr = 0;
  1263.     next = bh;
  1264.     do {
  1265.         struct buffer_head * tmp;
  1266.         block = *(b++);
  1267.  
  1268.         init_buffer(next, dev, block, end_buffer_io_async, NULL);
  1269.         set_bit(BH_Uptodate, &next->b_state);
  1270.  
  1271.         /*
  1272.          * When we use bmap, we define block zero to represent
  1273.          * a hole.  ll_rw_page, however, may legitimately
  1274.          * access block zero, and we need to distinguish the
  1275.          * two cases.
  1276.          */
  1277.         if (bmap && !block) {
  1278.             memset(next->b_data, 0, size);
  1279.             next->b_count--;
  1280.             continue;
  1281.         }
  1282.         tmp = get_hash_table(dev, block, size);
  1283.         if (tmp) {
  1284.             if (!buffer_uptodate(tmp)) {
  1285.                 if (rw == READ)
  1286.                     ll_rw_block(READ, 1, &tmp);
  1287.                 wait_on_buffer(tmp);
  1288.             }
  1289.             if (rw == READ) 
  1290.                 memcpy(next->b_data, tmp->b_data, size);
  1291.             else {
  1292.                 memcpy(tmp->b_data, next->b_data, size);
  1293.                 mark_buffer_dirty(tmp, 0);
  1294.             }
  1295.             brelse(tmp);
  1296.             next->b_count--;
  1297.             continue;
  1298.         }
  1299.         if (rw == READ)
  1300.             clear_bit(BH_Uptodate, &next->b_state);
  1301.         else
  1302.             set_bit(BH_Dirty, &next->b_state);
  1303.         arr[nr++] = next;
  1304.     } while (prev = next, (next = next->b_this_page) != NULL);
  1305.     prev->b_this_page = bh;
  1306.     
  1307.     if (nr) {
  1308.         ll_rw_block(rw, nr, arr);
  1309.         /* The rest of the work is done in mark_buffer_uptodate()
  1310.          * and unlock_buffer(). */
  1311.     } else {
  1312.         unsigned long flags;
  1313.         clear_bit(PG_locked, &page->flags);
  1314.         set_bit(PG_uptodate, &page->flags);
  1315.         wake_up(&page->wait);
  1316.         save_flags(flags);
  1317.         cli();
  1318.         free_async_buffers(bh);
  1319.         restore_flags(flags);
  1320.         after_unlock_page(page);
  1321.     }
  1322.     ++current->maj_flt;
  1323.     return 0;
  1324. }
  1325.  
  1326. /*
  1327.  * This is called by end_request() when I/O has completed.
  1328.  */
  1329. void mark_buffer_uptodate(struct buffer_head * bh, int on)
  1330. {
  1331.     if (on) {
  1332.         struct buffer_head *tmp = bh;
  1333.         set_bit(BH_Uptodate, &bh->b_state);
  1334.         /* If a page has buffers and all these buffers are uptodate,
  1335.          * then the page is uptodate. */
  1336.         do {
  1337.             if (!test_bit(BH_Uptodate, &tmp->b_state))
  1338.                 return;
  1339.             tmp=tmp->b_this_page;
  1340.         } while (tmp && tmp != bh);
  1341.         set_bit(PG_uptodate, &mem_map[MAP_NR(bh->b_data)].flags);
  1342.         return;
  1343.     }
  1344.     clear_bit(BH_Uptodate, &bh->b_state);
  1345. }
  1346.  
  1347. /*
  1348.  * Generic "readpage" function for block devices that have the normal
  1349.  * bmap functionality. This is most of the block device filesystems.
  1350.  * Reads the page asynchronously --- the unlock_buffer() and
  1351.  * mark_buffer_uptodate() functions propagate buffer state into the
  1352.  * page struct once IO has completed.
  1353.  */
  1354. int generic_readpage(struct file * file, struct page * page)
  1355. {
  1356.     struct dentry *dentry = file->f_dentry;
  1357.     struct inode *inode = dentry->d_inode;
  1358.     unsigned long block;
  1359.     int *p, nr[PAGE_SIZE/512];
  1360.     int i;
  1361.  
  1362.     atomic_inc(&page->count);
  1363.     set_bit(PG_locked, &page->flags);
  1364.     set_bit(PG_free_after, &page->flags);
  1365.     
  1366.     i = PAGE_SIZE >> inode->i_sb->s_blocksize_bits;
  1367.     block = page->offset >> inode->i_sb->s_blocksize_bits;
  1368.     p = nr;
  1369.     do {
  1370.         *p = inode->i_op->bmap(inode, block);
  1371.         i--;
  1372.         block++;
  1373.         p++;
  1374.     } while (i > 0);
  1375.  
  1376.     /* IO start */
  1377.     brw_page(READ, page, inode->i_dev, nr, inode->i_sb->s_blocksize, 1);
  1378.     return 0;
  1379. }
  1380.  
  1381. /*
  1382.  * Try to increase the number of buffers available: the size argument
  1383.  * is used to determine what kind of buffers we want.
  1384.  */
  1385. static int grow_buffers(int size)
  1386. {
  1387.     unsigned long page;
  1388.     struct buffer_head *bh, *tmp;
  1389.     struct buffer_head * insert_point;
  1390.     int isize;
  1391.  
  1392.     if ((size & 511) || (size > PAGE_SIZE)) {
  1393.         printk("VFS: grow_buffers: size = %d\n",size);
  1394.         return 0;
  1395.     }
  1396.  
  1397.     if (!(page = __get_free_page(GFP_BUFFER)))
  1398.         return 0;
  1399.     bh = create_buffers(page, size, 0);
  1400.     if (!bh) {
  1401.         free_page(page);
  1402.         return 0;
  1403.     }
  1404.  
  1405.     isize = BUFSIZE_INDEX(size);
  1406.     insert_point = free_list[isize];
  1407.  
  1408.     tmp = bh;
  1409.     while (1) {
  1410.         if (insert_point) {
  1411.             tmp->b_next_free = insert_point->b_next_free;
  1412.             tmp->b_prev_free = insert_point;
  1413.             insert_point->b_next_free->b_prev_free = tmp;
  1414.             insert_point->b_next_free = tmp;
  1415.         } else {
  1416.             tmp->b_prev_free = tmp;
  1417.             tmp->b_next_free = tmp;
  1418.         }
  1419.         insert_point = tmp;
  1420.         ++nr_buffers;
  1421.         if (tmp->b_this_page)
  1422.             tmp = tmp->b_this_page;
  1423.         else
  1424.             break;
  1425.     }
  1426.     tmp->b_this_page = bh;
  1427.     free_list[isize] = bh;
  1428.     mem_map[MAP_NR(page)].buffers = bh;
  1429.     buffermem += PAGE_SIZE;
  1430.     return 1;
  1431. }
  1432.  
  1433. /*
  1434.  * Can the buffer be thrown out?
  1435.  */
  1436. #define BUFFER_BUSY_BITS    ((1<<BH_Dirty) | (1<<BH_Lock) | (1<<BH_Protected))
  1437. #define buffer_busy(bh)        ((bh)->b_count || ((bh)->b_state & BUFFER_BUSY_BITS))
  1438.  
  1439. /*
  1440.  * try_to_free_buffers() checks if all the buffers on this particular page
  1441.  * are unused, and free's the page if so.
  1442.  *
  1443.  * Wake up bdflush() if this fails - if we're running low on memory due
  1444.  * to dirty buffers, we need to flush them out as quickly as possible.
  1445.  */
  1446. int try_to_free_buffers(struct page * page_map)
  1447. {
  1448.     struct buffer_head * tmp, * bh = page_map->buffers;
  1449.  
  1450.     tmp = bh;
  1451.     do {
  1452.         struct buffer_head * p = tmp;
  1453.  
  1454.         tmp = tmp->b_this_page;
  1455.         if (!buffer_busy(p))
  1456.             continue;
  1457.  
  1458.         wakeup_bdflush(0);
  1459.         return 0;
  1460.     } while (tmp != bh);
  1461.  
  1462.     tmp = bh;
  1463.     do {
  1464.         struct buffer_head * p = tmp;
  1465.         tmp = tmp->b_this_page;
  1466.         nr_buffers--;
  1467.         remove_from_queues(p);
  1468.         put_unused_buffer_head(p);
  1469.     } while (tmp != bh);
  1470.  
  1471.     /* Wake up anyone waiting for buffer heads */
  1472.     wake_up(&buffer_wait);
  1473.  
  1474.     /* And free the page */
  1475.     buffermem -= PAGE_SIZE;
  1476.     page_map->buffers = NULL;
  1477.     __free_page(page_map);
  1478.     return 1;
  1479. }
  1480.  
  1481. /* ================== Debugging =================== */
  1482.  
  1483. void show_buffers(void)
  1484. {
  1485.     struct buffer_head * bh;
  1486.     int found = 0, locked = 0, dirty = 0, used = 0, lastused = 0;
  1487.     int protected = 0;
  1488.     int nlist;
  1489.     static char *buf_types[NR_LIST] = {"CLEAN","LOCKED","DIRTY"};
  1490.  
  1491.     printk("Buffer memory:   %6dkB\n",buffermem>>10);
  1492.     printk("Buffer heads:    %6d\n",nr_buffer_heads);
  1493.     printk("Buffer blocks:   %6d\n",nr_buffers);
  1494.     printk("Buffer hashed:   %6d\n",nr_hashed_buffers);
  1495.  
  1496.     for(nlist = 0; nlist < NR_LIST; nlist++) {
  1497.       found = locked = dirty = used = lastused = protected = 0;
  1498.       bh = lru_list[nlist];
  1499.       if(!bh) continue;
  1500.  
  1501.       do {
  1502.         found++;
  1503.         if (buffer_locked(bh))
  1504.             locked++;
  1505.         if (buffer_protected(bh))
  1506.             protected++;
  1507.         if (buffer_dirty(bh))
  1508.             dirty++;
  1509.         if (bh->b_count)
  1510.             used++, lastused = found;
  1511.         bh = bh->b_next_free;
  1512.       } while (bh != lru_list[nlist]);
  1513.       printk("%8s: %d buffers, %d used (last=%d), "
  1514.          "%d locked, %d protected, %d dirty\n",
  1515.          buf_types[nlist], found, used, lastused,
  1516.          locked, protected, dirty);
  1517.     };
  1518. }
  1519.  
  1520.  
  1521. /* ===================== Init ======================= */
  1522.  
  1523. /*
  1524.  * allocate the hash table and init the free list
  1525.  * Use gfp() for the hash table to decrease TLB misses, use
  1526.  * SLAB cache for buffer heads.
  1527.  */
  1528. void __init buffer_init(void)
  1529. {
  1530.     int order = 5;        /* Currently maximum order.. */
  1531.     unsigned int nr_hash;
  1532.  
  1533.     nr_hash = (1UL << order) * PAGE_SIZE / sizeof(struct buffer_head *);
  1534.     hash_table = (struct buffer_head **) __get_free_pages(GFP_ATOMIC, order);
  1535.     
  1536.     if (!hash_table)
  1537.         panic("Failed to allocate buffer hash table\n");
  1538.     memset(hash_table, 0, nr_hash * sizeof(struct buffer_head *));
  1539.     bh_hash_mask = nr_hash-1;
  1540.  
  1541.     bh_cachep = kmem_cache_create("buffer_head",
  1542.                       sizeof(struct buffer_head),
  1543.                       0,
  1544.                       SLAB_HWCACHE_ALIGN, NULL, NULL);
  1545.     if(!bh_cachep)
  1546.         panic("Cannot create buffer head SLAB cache\n");
  1547.     /*
  1548.      * Allocate the reserved buffer heads.
  1549.      */
  1550.     while (nr_buffer_heads < NR_RESERVED) {
  1551.         struct buffer_head * bh;
  1552.  
  1553.         bh = kmem_cache_alloc(bh_cachep, SLAB_ATOMIC);
  1554.         if (!bh)
  1555.             break;
  1556.         put_unused_buffer_head(bh);
  1557.         nr_buffer_heads++;
  1558.     }
  1559.  
  1560.     lru_list[BUF_CLEAN] = 0;
  1561.     grow_buffers(BLOCK_SIZE);
  1562. }
  1563.  
  1564.  
  1565. /* ====================== bdflush support =================== */
  1566.  
  1567. /* This is a simple kernel daemon, whose job it is to provide a dynamic
  1568.  * response to dirty buffers.  Once this process is activated, we write back
  1569.  * a limited number of buffers to the disks and then go back to sleep again.
  1570.  */
  1571. static struct wait_queue * bdflush_wait = NULL;
  1572. static struct wait_queue * bdflush_done = NULL;
  1573. struct task_struct *bdflush_tsk = 0;
  1574.  
  1575. void wakeup_bdflush(int wait)
  1576. {
  1577.     if (current == bdflush_tsk)
  1578.         return;
  1579.     wake_up(&bdflush_wait);
  1580.     if (wait) {
  1581.         run_task_queue(&tq_disk);
  1582.         sleep_on(&bdflush_done);
  1583.     }
  1584. }
  1585.  
  1586.  
  1587. /* 
  1588.  * Here we attempt to write back old buffers.  We also try to flush inodes 
  1589.  * and supers as well, since this function is essentially "update", and 
  1590.  * otherwise there would be no way of ensuring that these quantities ever 
  1591.  * get written back.  Ideally, we would have a timestamp on the inodes
  1592.  * and superblocks so that we could write back only the old ones as well
  1593.  */
  1594.  
  1595. static int sync_old_buffers(void)
  1596. {
  1597.     int i;
  1598.     int ndirty, nwritten;
  1599.     int nlist;
  1600.     int ncount;
  1601.     struct buffer_head * bh, *next;
  1602.  
  1603.     sync_supers(0);
  1604.     sync_inodes(0);
  1605.  
  1606.     ncount = 0;
  1607. #ifdef DEBUG
  1608.     for(nlist = 0; nlist < NR_LIST; nlist++)
  1609. #else
  1610.     for(nlist = BUF_LOCKED; nlist <= BUF_DIRTY; nlist++)
  1611. #endif
  1612.     {
  1613.         ndirty = 0;
  1614.         nwritten = 0;
  1615.     repeat:
  1616.  
  1617.         bh = lru_list[nlist];
  1618.         if(bh) 
  1619.              for (i = nr_buffers_type[nlist]; i-- > 0; bh = next) {
  1620.                  /* We may have stalled while waiting for I/O to complete. */
  1621.                  if(bh->b_list != nlist) goto repeat;
  1622.                  next = bh->b_next_free;
  1623.                  if(!lru_list[nlist]) {
  1624.                      printk("Dirty list empty %d\n", i);
  1625.                      break;
  1626.                  }
  1627.                  
  1628.                  /* Clean buffer on dirty list?  Refile it */
  1629.                  if (nlist == BUF_DIRTY && !buffer_dirty(bh) && !buffer_locked(bh)) {
  1630.                      refile_buffer(bh);
  1631.                      continue;
  1632.                  }
  1633.                   
  1634.                   /* Unlocked buffer on locked list?  Refile it */
  1635.                   if (nlist == BUF_LOCKED && !buffer_locked(bh)) {
  1636.                       refile_buffer(bh);
  1637.                       continue;
  1638.                   }
  1639.                  
  1640.                  if (buffer_locked(bh) || !buffer_dirty(bh))
  1641.                       continue;
  1642.                  ndirty++;
  1643.                  if(time_before(jiffies, bh->b_flushtime))
  1644.                     continue;
  1645.                  nwritten++;
  1646.                  next->b_count++;
  1647.                  bh->b_count++;
  1648.                  bh->b_flushtime = 0;
  1649. #ifdef DEBUG
  1650.                  if(nlist != BUF_DIRTY) ncount++;
  1651. #endif
  1652.                  ll_rw_block(WRITE, 1, &bh);
  1653.                  bh->b_count--;
  1654.                  next->b_count--;
  1655.              }
  1656.     }
  1657.     run_task_queue(&tq_disk);
  1658. #ifdef DEBUG
  1659.     if (ncount) printk("sync_old_buffers: %d dirty buffers not on dirty list\n", ncount);
  1660.     printk("Wrote %d/%d buffers\n", nwritten, ndirty);
  1661. #endif
  1662.     run_task_queue(&tq_disk);
  1663.     return 0;
  1664. }
  1665.  
  1666.  
  1667. /* This is the interface to bdflush.  As we get more sophisticated, we can
  1668.  * pass tuning parameters to this "process", to adjust how it behaves. 
  1669.  * We would want to verify each parameter, however, to make sure that it 
  1670.  * is reasonable. */
  1671.  
  1672. asmlinkage int sys_bdflush(int func, long data)
  1673. {
  1674.     int i, error = -EPERM;
  1675.  
  1676.     lock_kernel();
  1677.     if (!capable(CAP_SYS_ADMIN))
  1678.         goto out;
  1679.  
  1680.     if (func == 1) {
  1681.          error = sync_old_buffers();
  1682.          goto out;
  1683.     }
  1684.  
  1685.     /* Basically func 1 means read param 1, 2 means write param 1, etc */
  1686.     if (func >= 2) {
  1687.         i = (func-2) >> 1;
  1688.         error = -EINVAL;
  1689.         if (i < 0 || i >= N_PARAM)
  1690.             goto out;
  1691.         if((func & 1) == 0) {
  1692.             error = put_user(bdf_prm.data[i], (int*)data);
  1693.             goto out;
  1694.         }
  1695.         if (data < bdflush_min[i] || data > bdflush_max[i])
  1696.             goto out;
  1697.         bdf_prm.data[i] = data;
  1698.         error = 0;
  1699.         goto out;
  1700.     };
  1701.  
  1702.     /* Having func 0 used to launch the actual bdflush and then never
  1703.      * return (unless explicitly killed). We return zero here to 
  1704.      * remain semi-compatible with present update(8) programs.
  1705.      */
  1706.     error = 0;
  1707. out:
  1708.     unlock_kernel();
  1709.     return error;
  1710. }
  1711.  
  1712. /* This is the actual bdflush daemon itself. It used to be started from
  1713.  * the syscall above, but now we launch it ourselves internally with
  1714.  * kernel_thread(...)  directly after the first thread in init/main.c */
  1715.  
  1716. /* To prevent deadlocks for a loop device:
  1717.  * 1) Do non-blocking writes to loop (avoids deadlock with running
  1718.  *    out of request blocks).
  1719.  * 2) But do a blocking write if the only dirty buffers are loop buffers
  1720.  *    (otherwise we go into an infinite busy-loop).
  1721.  * 3) Quit writing loop blocks if a freelist went low (avoids deadlock
  1722.  *    with running out of free buffers for loop's "real" device).
  1723. */
  1724. int bdflush(void * unused) 
  1725. {
  1726.     int i;
  1727.     int ndirty;
  1728.     int nlist;
  1729.     int ncount;
  1730.     struct buffer_head * bh, *next;
  1731.     int major;
  1732.     int wrta_cmd = WRITEA;    /* non-blocking write for LOOP */
  1733.  
  1734.     /*
  1735.      *    We have a bare-bones task_struct, and really should fill
  1736.      *    in a few more things so "top" and /proc/2/{exe,root,cwd}
  1737.      *    display semi-sane things. Not real crucial though...  
  1738.      */
  1739.  
  1740.     current->session = 1;
  1741.     current->pgrp = 1;
  1742.     sprintf(current->comm, "kflushd");
  1743.     bdflush_tsk = current;
  1744.  
  1745.     /*
  1746.      *    As a kernel thread we want to tamper with system buffers
  1747.      *    and other internals and thus be subject to the SMP locking
  1748.      *    rules. (On a uniprocessor box this does nothing).
  1749.      */
  1750.     lock_kernel();
  1751.          
  1752.     for (;;) {
  1753. #ifdef DEBUG
  1754.         printk("bdflush() activated...");
  1755. #endif
  1756.  
  1757.         CHECK_EMERGENCY_SYNC
  1758.  
  1759.         ncount = 0;
  1760. #ifdef DEBUG
  1761.         for(nlist = 0; nlist < NR_LIST; nlist++)
  1762. #else
  1763.         for(nlist = BUF_LOCKED; nlist <= BUF_DIRTY; nlist++)
  1764. #endif
  1765.          {
  1766.              ndirty = 0;
  1767.          repeat:
  1768.  
  1769.              bh = lru_list[nlist];
  1770.              if(bh) 
  1771.                   for (i = nr_buffers_type[nlist]; i-- > 0 && ndirty < bdf_prm.b_un.ndirty; 
  1772.                        bh = next) {
  1773.                       /* We may have stalled while waiting for I/O to complete. */
  1774.                       if(bh->b_list != nlist) goto repeat;
  1775.                       next = bh->b_next_free;
  1776.                       if(!lru_list[nlist]) {
  1777.                           printk("Dirty list empty %d\n", i);
  1778.                           break;
  1779.                       }
  1780.                       
  1781.                       /* Clean buffer on dirty list?  Refile it */
  1782.                       if (nlist == BUF_DIRTY && !buffer_dirty(bh)) {
  1783.                           refile_buffer(bh);
  1784.                           continue;
  1785.                       }
  1786.                       
  1787.                       /* Unlocked buffer on locked list?  Refile it */
  1788.                       if (nlist == BUF_LOCKED && !buffer_locked(bh)) {
  1789.                           refile_buffer(bh);
  1790.                           continue;
  1791.                       }
  1792.                       
  1793.                       if (buffer_locked(bh) || !buffer_dirty(bh))
  1794.                            continue;
  1795.                       major = MAJOR(bh->b_dev);
  1796.                       /* Should we write back buffers that are shared or not??
  1797.                          currently dirty buffers are not shared, so it does not matter */
  1798.                       next->b_count++;
  1799.                       bh->b_count++;
  1800.                       ndirty++;
  1801.                       bh->b_flushtime = 0;
  1802.                       if (major == LOOP_MAJOR) {
  1803.                           ll_rw_block(wrta_cmd,1, &bh);
  1804.                           wrta_cmd = WRITEA;
  1805.                           if (buffer_dirty(bh))
  1806.                               --ndirty;
  1807.                       }
  1808.                       else
  1809.                       ll_rw_block(WRITE, 1, &bh);
  1810. #ifdef DEBUG
  1811.                       if(nlist != BUF_DIRTY) ncount++;
  1812. #endif
  1813.                       bh->b_count--;
  1814.                       next->b_count--;
  1815.                   }
  1816.          }
  1817. #ifdef DEBUG
  1818.         if (ncount) printk("sys_bdflush: %d dirty buffers not on dirty list\n", ncount);
  1819.         printk("sleeping again.\n");
  1820. #endif
  1821.         /* If we didn't write anything, but there are still
  1822.          * dirty buffers, then make the next write to a
  1823.          * loop device to be a blocking write.
  1824.          * This lets us block--which we _must_ do! */
  1825.         if (ndirty == 0 && nr_buffers_type[BUF_DIRTY] > 0 && wrta_cmd != WRITE) {
  1826.             wrta_cmd = WRITE;
  1827.             continue;
  1828.         }
  1829.         run_task_queue(&tq_disk);
  1830.         wake_up(&bdflush_done);
  1831.         
  1832.         /* If there are still a lot of dirty buffers around, skip the sleep
  1833.            and flush some more */
  1834.         if(ndirty == 0 || nr_buffers_type[BUF_DIRTY] <= nr_buffers * bdf_prm.b_un.nfract/100) {
  1835.             spin_lock_irq(¤t->sigmask_lock);
  1836.             flush_signals(current);
  1837.             spin_unlock_irq(¤t->sigmask_lock);
  1838.  
  1839.             interruptible_sleep_on(&bdflush_wait);
  1840.         }
  1841.     }
  1842. }
  1843.